package com.itheima.api.array.demo02;

public class SortDemo02 {
    public static void main(String[] args) {

        System.out.println("-----------");
        int[] arr = {3,2,1,6,9,7,5,4,8};

        traverse(arr);
        System.out.println();
        bubbleSort(arr);
//        quickSort(arr, 0, arr.length - 1);
        traverse(arr);

    }

    public static void quickSort(int[] arr, int minIndex, int maxIndex){
        if (minIndex < maxIndex) {
            int partitionIndex = partition(arr, minIndex, maxIndex);
            quickSort(arr, minIndex, partitionIndex - 1);
            quickSort(arr, partitionIndex + 1, maxIndex);
        }
    }

//    int[] arr = {1,2,3,6,9,7,5,4,8};3,2

    public static int partition(int[] arr, int minIndex, int maxIndex){

        while (minIndex < maxIndex) {
            int temp = arr[minIndex];
            while (minIndex < maxIndex) {
                if (arr[maxIndex] <= temp) {
                    arr[minIndex] = arr[maxIndex];
                    minIndex++;//1
                    break;
                }
                maxIndex--;//2
            }
            while (minIndex < maxIndex) {
                if (arr[minIndex] > temp) {
                    arr[maxIndex] = arr[minIndex];
                    minIndex++;
                    break;
                }
                minIndex++;
            }
            arr[minIndex] = temp;
        }
        return maxIndex;
    }

    public static void traverse(int[] arr){
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + ",");
        }
    }

    public static void bubbleSort(int[] arr){

        for (int y = 0; y < arr.length - 1; y++) {
            for (int i = 0; i < arr.length - 1 - y; i++) {
                if (arr[i] > arr[i + 1]) {
                    int temp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = temp;
                }
            }
        }
    }
}
